﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace PictrueSimpleSyndication
{
    public class XmlSubscribeInfo : SubscribeInfo
    {
        /// <summary>
        /// 订阅类型
        /// </summary>
        public string SubscribeType { get; set; }

        /// <summary>
        /// 子集的内容
        /// </summary>
        public List<XmlSubscribeInfo> ChildSubscribeInfos { get; set; }
    }

    public class NetDataSubscribeList : IDataSubscribeList
    {
        private const string CONFIG_FILE_NAME = "Subscribe.config";

        private XmlDocument Document = new XmlDocument();

        private List<XmlSubscribeInfo> _Roots = new List<XmlSubscribeInfo>();
        private List<XmlSubscribeInfo> _All = new List<XmlSubscribeInfo>();

        public NetDataSubscribeList()
        {
            if (File.Exists(CONFIG_FILE_NAME))
                Document.Load(CONFIG_FILE_NAME);

            var nodes = Document.SelectNodes("/System/Subscribe/Item");

            if (nodes == null)
                return;

            foreach (XmlNode item in nodes)
            {
                var root_node = new XmlSubscribeInfo
                {
                    ChildSubscribeInfos = new List<XmlSubscribeInfo>(),
                    Identification = Guid.NewGuid().ToString("N"),
                    Title = item.Attributes["Title"]?.Value,
                    SubscribeType = item.Attributes["SubscribeType"]?.Value,
                };

                _Roots.Add(root_node);
                _All.Add(root_node);

                foreach (XmlNode child_item in item.ChildNodes)
                {
                    var child_node = new XmlSubscribeInfo
                    {
                        ChildSubscribeInfos = new List<XmlSubscribeInfo>(),
                        Identification = Guid.NewGuid().ToString("N"),
                        Title = child_item.Attributes["Title"]?.Value,
                        SubscribeType = child_item.Attributes["SubscribeType"]?.Value,
                    };

                    root_node.ChildSubscribeInfos.Add(child_node);
                    _All.Add(child_node);
                }
            }
        }

        public IEnumerable<SubscribeInfo> GetAllChildSubscribeInfo(string identification)
        {
            return _Roots.FirstOrDefault(n => n.Identification == identification)?.ChildSubscribeInfos;
        }

        public IDataContentList GetDataContentList(string identification)
        {
            var subscribetype = _All.FirstOrDefault(n => n.Identification == identification)?.SubscribeType;

            if (subscribetype == "NetSubscribe")
            {
                return new NetDataContentList();
            }

            return null;
        }

        public IEnumerable<SubscribeInfo> GetRootSubscribeInfo()
        {
            return _Roots;
        }
    }
}
